package com.open.capacity.salary.service.impl;

import com.open.capacity.model.system.SysUser;
import com.open.capacity.reimburse.util.uuid.UUIDUtils;
import com.open.capacity.salary.entity.GzRecordTax;
import com.open.capacity.utils.SysUserUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.open.capacity.commons.PageResult;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.open.capacity.commons.CodeEnum;

import java.math.BigDecimal;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.collections4.MapUtils;

import com.open.capacity.salary.entity.GzTax;
import com.open.capacity.salary.dao.GzTaxDao;
import com.open.capacity.salary.service.GzTaxService;
import org.springframework.transaction.annotation.Transactional;


@Service
public class GzTaxServiceImpl implements GzTaxService {

    @Autowired
    private GzTaxDao gzTaxDao;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int init(String companyId) {
        gzTaxDao.deleteByCompanyId(companyId);
        return gzTaxDao.init(companyId);
    }

    /**
     * 添加
     *
     * @param gzTax
     */
    public int save(GzTax gzTax) {
        SysUser loginUser = SysUserUtil.getLoginAppUser();

        gzTax.setUpdateUserid(loginUser.getId());
        gzTax.setUpdateUsername(loginUser.getRealName());
        gzTax.setId(UUIDUtils.getOriginalUUIDWithoutBar());
        gzTax.setUpdateTime(new Date());
        gzTax.setStatus(1);
        return gzTaxDao.save(gzTax);
    }

    /**
     * 修改
     *
     * @param gzTax
     */
    public int update(GzTax gzTax) {
        SysUser loginUser = SysUserUtil.getLoginAppUser();

        gzTax.setUpdateUserid(loginUser.getId());
        gzTax.setUpdateUsername(loginUser.getRealName());
        gzTax.setUpdateTime(new Date());
        return gzTaxDao.update(gzTax);
    }


    /**
     * 删除
     *
     * @param id
     */
    public int delete(String id) {
        return gzTaxDao.delete(id);
    }

    /**
     * 查询记录
     *
     * @param id
     * @return
     */
    public GzTax findById(String id) {
        return gzTaxDao.findById(id);
    }

    /**
     * 计算税额
     *
     * @param companyId
     * @param isIncludeTax 是否含税
     * @param income       收入合计
     * @return
     */
    @Override
    public GzRecordTax calcTax(String companyId, Integer isIncludeTax, BigDecimal income) {
        Map<String, Object> params = new HashMap<>();
        params.put("companyId", companyId);
        params.put("category", 1);
        List<GzTax> list = gzTaxDao.findAll(params);
        GzRecordTax result = new GzRecordTax();
        if (isIncludeTax.equals(1)) { //含税
            BigDecimal legalReduce = list.stream().filter(t -> t.getStatus().equals(2) && StringUtils.isEmpty(t.getTaxCode())).findFirst().get().getTaxInclusiveStart();
            if (income.compareTo(legalReduce) <= 0) { //低于法定扣除数和统减金额
                result.setTax(BigDecimal.ZERO);
                result.setTaxableIncome(BigDecimal.ZERO);
            } else {
                income = income.subtract(legalReduce);//减去法定扣除数和统减金额
                result.setTaxableIncome(income); //应纳所得税额
                for (GzTax item : list) {
                    result.setTax(BigDecimal.valueOf(item.getRate()));
                    if (income.compareTo(item.getTaxInclusiveEnd()) > 0) {
                        income = income.subtract(item.getMoney());
                        result.setDeduction(item.getMoney());
                    } else {
                        BigDecimal amount = result.getTaxableIncome().multiply(result.getTax()).divide(BigDecimal.valueOf(100));
                        result.setDeduction(item.getMoney());
                        result.setTaxAmount(amount.subtract(item.getMoney()));
                        result.setActualTax(amount.subtract(item.getMoney()));
                        break;
                    }
                }
            }
        }else if (isIncludeTax.equals(2)) { //不含税
            BigDecimal legalReduce = list.stream().filter(t -> t.getStatus().equals(2) && StringUtils.isEmpty(t.getTaxCode())).findFirst().get().getTaxInclusiveStart();
            if (income.compareTo(legalReduce) <= 0) { //低于法定扣除数和统减金额
                result.setTax(BigDecimal.ZERO);
                result.setTaxableIncome(BigDecimal.ZERO);
            } else {
                income = income.subtract(legalReduce);//减去法定扣除数和统减金额
                result.setTaxableIncome(income); //应纳所得税额
                for (GzTax item : list) {
                    result.setTax(BigDecimal.valueOf(item.getRate()));
                    if (income.compareTo(item.getTaxInclusiveEnd()) > 0) {
                        income = income.subtract(item.getMoney());
                        result.setDeduction(item.getMoney());
                    } else {
                        BigDecimal amount = result.getTaxableIncome().multiply(result.getTax()).divide(BigDecimal.valueOf(100));
                        result.setDeduction(item.getMoney());
                        result.setTaxAmount(amount.subtract(item.getMoney()));
                        result.setActualTax(amount.subtract(item.getMoney()));
                        break;
                    }
                }
            }
        }
        return result;
    }

    /**
     * 分页
     *
     * @param params
     * @return
     */
    public PageResult<GzTax> pageAll(Map<String, Object> params) {
        //设置分页信息，分别是当前页数和每页显示的总记录数【记住：必须在mapper接口中的方法执行之前设置该分页信息】
        if (MapUtils.getInteger(params, "page") != null && MapUtils.getInteger(params, "limit") != null)
            PageHelper.startPage(MapUtils.getInteger(params, "page"), MapUtils.getInteger(params, "limit"), true);

        List<GzTax> list = gzTaxDao.findAll(params);
        PageInfo<GzTax> pageInfo = new PageInfo(list);

        return PageResult.<GzTax>builder().data(pageInfo.getList()).resp_code(CodeEnum.SUCCESS.getCode()).count(pageInfo.getTotal()).build();
    }

    /**
     * 列表
     *
     * @param params
     * @return
     */
    public List<GzTax> findAll(Map<String, Object> params) {
        return gzTaxDao.findAll(params);
    }

}
